package my.myorm.tool.jdbc;

import my.myorm.tool.orm.DataTypeDefault;

import java.util.*;
import java.sql.ResultSet;
import java.sql.Timestamp;

/**
 * 默认javabean，若resultset中的字段不属于任何表（如count(*)）,则该字段被封装于DefaultBean中
 *
 * @author Skeven Huang
 * @version 1.0
 */
public class DefaultBean implements RowMapper {
    private int resulttype=0;
    private Map tdbdata=null;//tdb
    private Map<String, List<Object[]>> data = new HashMap<String, List<Object[]>>();//sql

    /**
     * 获取指定的key对应的value
     *
     * @param key
     * @return
     * @throws Exception
     */
    private Object get(Object key) throws Exception {
        if (key == null)
            return null;
        if (!(key instanceof String))
            return null;

        System.out.println("key:" + key + resulttype);
        
        if(resulttype==1){//TDB
        	
            Iterator it=tdbdata.keySet().iterator();   
            while(it.hasNext()){   
                 String key0 = null;   
                 String value;   
                 key0=it.next().toString();   
                 value=(String) tdbdata.get(key0);   
                 System.out.println(key0+"--"+value);   
            }  
            
            return tdbdata==null?null:tdbdata.get(key);
        }


        String thekey = (key + "").toLowerCase();
        List<Object[]> list = data.get(thekey);
        if (list != null) {// 说明传过来的是column
            if (list.size() == 0)
                return null;
            else
                return list.get(0)[1];
        }
        // 说明传过来的不是column
        String table = "";
        String column = "";
        int index = thekey.indexOf(".");
        if (index < 0) {
            column = thekey;
        } else {
            table = thekey.substring(0, index);
            column = thekey.substring(index + 1);
        }
        list = data.get(column);
        if (list == null || list.size() == 0)
            return null;
        if (list.size() == 1)
            return list.get(0)[1];
        if (table.equals(""))
            return list.get(0)[1];
        for (int i = 0; i < list.size(); i++) {
            Object[] objs = list.get(i);
            if ((objs[0] + "").equals(table)) {
                return objs[1];
            }
        }
        return null;
    }

    /**
     * 写入key-value对
     *
     * @param key
     * @return
     * @throws Exception
     */
    private void put(Object key, Object value) throws Exception {
        if (key == null) throw new Exception("key must not be null");
        if (!(key instanceof String)) throw new Exception("key should  be String");
        String thekey = (key + "").toLowerCase();
        int index = thekey.indexOf(".");
        if (index < 0) {
            throw new Exception("param err,at least one point");
        }
        index = thekey.indexOf(".");
        String table = thekey.substring(0, index);
        String column = thekey.substring(index + 1);
        if (data.get(column) == null) {
            data.put(column, new LinkedList<Object[]>());
        }
        List<Object[]> list = data.get(column);
        list.add(new Object[]{table, value});
    }

    /**
     * 获取指定的key对应的value，转换为byte类型
     *
     * @param key
     * @return
     * @throws Exception
     */
    public int getByte(String key) throws Exception {
        Object o = get(key);
        if (o == null) {
            return DataTypeDefault.DEFAULT_BYTE;
        } else {
            try {
                return Byte.parseByte(o.toString().trim());
            } catch (Exception ex) {
                return DataTypeDefault.DEFAULT_BYTE;
            }
        }
    }

    /**
     * 获取指定的key对应的value，转换为short类型
     *
     * @param key
     * @return
     * @throws Exception
     */
    public int getShort(String key) throws Exception {
        Object o = get(key);
        if (o == null) {
            return DataTypeDefault.DEFAULT_SHORT;
        } else {
            try {
                return Short.parseShort(o.toString().trim());
            } catch (Exception ex) {
                return DataTypeDefault.DEFAULT_SHORT;
            }
        }
    }

    /**
     * 获取指定的key对应的value，转换为int类型
     *
     * @param key
     * @return
     * @throws Exception
     */
    public int getInt(String key) throws Exception {
        Object o = get(key);
        if (o == null) {
            return DataTypeDefault.DEFAULT_INT;
        } else {
            try {
                return Integer.parseInt(o.toString().trim());
            } catch (Exception ex) {
                return DataTypeDefault.DEFAULT_INT;
            }
        }
    }

    /**
     * 获取指定的key对应的value，转换为long类型
     *
     * @param key
     * @return
     * @throws Exception
     */
    public long getLong(String key) throws Exception {
        Object o = get(key);
        if (o == null) {
            return DataTypeDefault.DEFAULT_LONG;
        } else {
            try {
                return Long.parseLong(o.toString().trim());
            } catch (Exception ex) {
                return DataTypeDefault.DEFAULT_LONG;
            }
        }
    }

    /**
     * 获取指定的key对应的value，转换为float类型
     *
     * @param key
     * @return
     * @throws Exception
     */
    public float getFloat(String key) throws Exception {
        Object o = get(key);
        if (o == null) {
            return DataTypeDefault.DEFAULT_FLOAT;
        } else {
            try {
                return Float.parseFloat(o.toString().trim());
            } catch (Exception ex) {
                return DataTypeDefault.DEFAULT_FLOAT;
            }
        }
    }

    /**
     * 获取指定的key对应的value，转换为double类型
     *
     * @param key
     * @return
     * @throws Exception
     */
    public double getDouble(String key) throws Exception {
        Object o = get(key);
        if (o == null) {
            return DataTypeDefault.DEFAULT_DOUBLE;
        } else {
            try {
                return Double.parseDouble(o.toString().trim());
            } catch (Exception ex) {
                return DataTypeDefault.DEFAULT_DOUBLE;
            }
        }
    }

    /**
     * 获取指定的key对应的value，Boolean
     *
     * @param key
     * @return
     * @throws Exception
     */
    public boolean getBoolean(String key) throws Exception {
        Object o = get(key);
        if (o == null || !(o instanceof Boolean)) {
            return DataTypeDefault.DEFAULT_BOOLEAN;
        } else {
            try {
                return Boolean.parseBoolean(o.toString().trim());
            } catch (Exception ex) {
                return DataTypeDefault.DEFAULT_BOOLEAN;
            }
        }
    }

    /**
     * 获取指定的key对应的value，转换为String类型
     *
     * @param key
     * @return
     * @throws Exception
     */
    public String getString(String key) throws Exception {
        Object o = get(key);
        if (o == null) {
            return DataTypeDefault.DEFAULT_STRING;
        } else {
            return o.toString().trim();
        }
    }

    /**
     * 获取指定的key对应的value，转换为java.util.Date类型
     *
     * @param key
     * @return
     * @throws Exception
     */
    public Date getDate(String key) throws Exception {
        Object o = get(key);
        if (o == null || !((o instanceof java.sql.Date) || (o instanceof java.sql.Time) || (o instanceof Timestamp))) {
            return DataTypeDefault.DEFAULT_DATE;
        } else {
            if (o instanceof java.sql.Date) {
                return new Date(((java.sql.Date) o).getTime());
            } else if (o instanceof java.sql.Time) {
                return new Date(((java.sql.Time) o).getTime());
            } else {
                return new Date(((java.sql.Timestamp) o).getTime());
            }
        }
    }

    /**
     * ResultSet到DefaultBean的转换函数
     *
     * @param rs
     * @param columns
     * @return
     * @throws Exception
     */
    public Object mapRow(ResultSet rs, Map<String, String> columns) throws Exception {
        String[] labels = columns.keySet().toArray(new String[0]);
        for (int i = 0; i < labels.length; i++) {
            String table = labels[i].substring(0, labels[i].indexOf("."));
            if (table.equals("_default_table_name_")) {
                put(labels[i], rs.getObject(labels[i].substring(table.length() + 1)));
            } else {
                put(labels[i], rs.getObject(labels[i]));
            }
        }
        labels = null;
        return this;
    }

    public void setResulttype(int resulttype) {
        this.resulttype = resulttype;
    }

    public void setTdbdata(Map tdbdata) {
        this.tdbdata = tdbdata;
    }
}
